package com.karlis.users.dao.impl;

import java.sql.*;
import javax.sql.*;
import com.karlis.users.dao.UsersDAO;
import com.karlis.users.model.Users;

public class JdbcUsersDAO implements UsersDAO {

	private DataSource dataSource;
	
	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}
	
	public void insert(Users user) {
		String sql = "INSERT INTO USERS " + "(USER_ID, USERNAME, PASSWORD, ENABLED) VALUES (?, ?, ?, ?)";
		Connection conn = null;
		
		try {
			conn = dataSource.getConnection();
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setInt(1, user.getUserId());
			ps.setString(2, user.getUsername());
			ps.setString(3, user.getPassword());
			ps.setBoolean(4, user.getEnabled());
			ps.executeUpdate();
			ps.close();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {}
			}
		}
		
	}

	public Users findByUsersId(int userID) {
		String sql = "SELECT * FROM USERS WHERE USER_ID = ?";
		Connection conn = null;
		try {
			conn = dataSource.getConnection();
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setInt(1, userID);
			Users user = null;
			ResultSet rs = ps.executeQuery();
			if (rs.next()) {
				user = new Users(
						rs.getInt("USER_ID"),
						rs.getString("USERNAME"),
						rs.getString("PASSWORD"),
						rs.getBoolean("ENABLED")
						);
			}
			rs.close();
			ps.close();
			return user;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {}
			}
		}
		
	}
	
}